package Concurrency2.Chapter08_Pattern;

/**
 * Instruction：
 * Author：@author MaLi
 */
public class T01_Singleton {
    //饿汉式
    public static class Singleton1 {
        private static Singleton1 instance;

        static {
            instance = new Singleton1();
        }

        private Singleton1() {
        }

        public static Singleton1 getInstance() {
            return instance;
        }
    }

    //饱汉式1
    public static class Singleton2{
        private static Singleton2 instance;

        private Singleton2() {
        }

        public synchronized static Singleton2 getInstance() {
            instance = new Singleton2();
            return instance;
        }
    }

    //饱汉式2
    public static class Singleton3{
        private static Singleton3 instance;

        private Singleton3() {
        }

        public static Singleton3 getInstance() {
            if (instance == null) {
                synchronized (Singleton3.class) {
                    if (instance==null) {
                        instance = new Singleton3();
                    }
                }
            }
            return instance;
        }
    }

    //饱汉式3: 防止重排序
    public static class Singleton4{
        private static volatile Singleton4 instance;

        private Singleton4() {
        }

        public static Singleton4 getInstance() {
            if (instance == null) {
                synchronized (Singleton4.class) {
                    if (instance==null) {
                        instance = new Singleton4();
                    }
                }
            }
            return instance;
        }
    }

    //饱汉式4: 靠类加载器保证只会加载一次
    public static class Singleton5{
        private static class Holder{
            public static Singleton5 instance = new Singleton5();
        }

        private Singleton5() {
        }

        public static Singleton5 getInstance() {
            return Holder.instance;
        }
    }
}
